# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt

n = 10                            # 值可更改
X1 = [-1 + i / 5 for i in range(n + 1)]
X2 = [np.cos((2 * i + 1) * np.pi / (2 * n + 2)) for i in range(n + 1)]
F1 = [1 / (1 + 25 * (x**2)) for x in X1]
F2 = [1 / (1 + 25 * (x**2)) for x in X2]
x = np.linspace(-1, 1, 100)


S = P = 0
for i in range(n + 1):

    # 构造 xi=-1 + i/5 ，i= 0,1,2...n,时的拉格朗日插值多项式 S(x)
    def l1(i):
        l1 = 1
        for j in range(n + 1):
            if i != j:
                l1 = l1 * (x - X1[j]) / (X1[i] - X1[j])
        return l1
    S = S + F1[i] * l1(i)

    # 构造 xi=cos((2 * i + 1) * pi / (2 * n + 2)) ，i= 0,1,2..n,时的拉格朗日插值多项式P(x)
    def l2(i):
        l2 = 1
        for j in range(n + 1):
            if i != j:
                l2 = l2 * (x - X2[j]) / (X2[i] - X2[j])
        return l2

    P = P + F2[i] * l2(i)

# 定义F(x)
F = 1 / (1 + 25 * (x**2))

# 绘制函数 S(x)、P(x)、F(x)的图像

plt.figure(figsize=(8, 4))
plt.plot(x, S, label='$S(x)$', color='red', linewidth=2)
plt.plot(x, P, 'g--', label='$P(x)$', lw=3)
plt.plot(x, F, label='$F(x)$', color='gray', lw=2)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Lagrange')
plt.ylim(-1, 4)
plt.legend()
plt.show()
